const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const MongoClient = require('mongodb').MongoClient

app.set('view engine', 'ejs')

app.use(bodyParser.urlencoded({
    extended: true
}))
var db
MongoClient.connect('mongodb://rlwb:zhangli1992@ds060369.mlab.com:60369/mongotest', (err, database) => {
    if (err) return console.log(err)
    db = database
    app.listen(3000, () => {
        console.log('listening on 3000')
        // app.get('/', (req, res) => {
        //     //    res.send('Hello World!')
        //     res.sendFile(__dirname + '/index.html')
        //     db.collection('users').find().toArray(function(err, results) {
        //         console.log(results)
        //     })
        // })
        app.get('/', (req, res) => {
            db.collection('quotes').find().toArray((err, result) => {
                if (err) return console.log(err)
                // renders index.ejs
                res.render('index.ejs', {
                    quotes: result
                })
            })
        })
        // console.log(__dirname)
        app.post('/quotes', (req, res) => {
            db.collection('quotes').save(req.body, (err, result) => {
                if (err) return console.log(err)
                console.log('保存成功！')
                res.redirect('/')
            })
        })
    })
})